What is lodash.identity?
The lodash.identity package is a utility function that returns the first argument it receives. It is often used as a default iteratee or callback function in various lodash methods.
What are lodash.identity's main functionalities?
Basic Usage
The basic usage of lodash.identity is to return the first argument it receives. In this example, it simply returns the number 5.
const identity = require('lodash.identity');
console.log(identity(5)); // Output: 5
Using with Array Methods
Lodash.identity can be used as a callback function in array methods like map. In this example, it returns each element of the array as is.
const identity = require('lodash.identity');
const arr = [1, 2, 3, 4];
const result = arr.map(identity);
console.log(result); // Output: [1, 2, 3, 4]
Using with Lodash Methods
Lodash.identity can be used with other lodash methods like filter. In this example, it returns all elements of the array that are truthy.
const _ = require('lodash');
const identity = require('lodash.identity');
const arr = [1, 2, 3, 4];
const result = _.filter(arr, identity);
console.log(result); // Output: [1, 2, 3, 4]
Other packages similar to lodash.identity
ramda
Ramda is a functional programming library for JavaScript. It provides a similar identity function called R.identity, which also returns the first argument it receives. Ramda focuses more on functional programming paradigms compared to lodash.
underscore
Underscore is another utility library for JavaScript that provides a similar identity function. The _.identity function in Underscore works the same way as lodash.identity, returning the first argument it receives. Underscore is often considered a predecessor to lodash.
lodash.identity v3.0.0
The modern build of lodash’s _.identity
exported as a Node.js/io.js module.
Installation
Using npm:
$ {sudo -H} npm i -g npm
$ npm i --save lodash.identity
In Node.js/io.js:
var identity = require('lodash.identity');
See the documentation or package source for more details.